<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}供应商`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="供应商名" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="请填写供应商名" clearable></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="drawerProps.row!.type" placeholder="请选择类型" filterable clearable>
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商地址" prop="address">
        <el-input v-model="drawerProps.row!.address" placeholder="请填写供应商地址" clearable></el-input>
      </el-form-item>
      <el-form-item label="供应商电话" prop="phone">
        <el-input v-model="drawerProps.row!.phone" placeholder="请填写供应商电话" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="SpecDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Supplier } from "@/api/interface";

const rules = reactive({
  name: [{ required: true, message: "请填写供应商名" }],
  address: [{ required: true, message: "请填写供应商地址" }],
  type: [{ required: true, message: "请选择供类型" }],
  phone: [{ required: true, message: "请填写供应商电话" }]
});
const typeList = ref([
  { id: 10, name: "自营" },
  { id: 20, name: "供应商" },
  { id: 30, name: "合作单位" }
]);
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Supplier.ResSpecList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}供应商成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
